<template>
	<div class="kyc-email-modal px-[25px] md:px-[35px] pt-4 pb-10">
		<BaseTip text="Verification code has been sent to g***n@uponly.io" />
		<div ref="inputListRef" class="px-10 mt-16 flex justify-between">
			<input
				v-for="index in 6"
				:key="index"
				type="text"
				maxlength="1"
				class="w-10 bg-transparent border-x-0 border-t-0 border-b border-border-3 focus:border-primary caret-primary outline-none text-center text-[20px] pb-3 text-t-1 transition-all"
				@keydown="onInput($event, index - 1)" />
		</div>
		<BaseButton class="mt-10" type="primary" @click="onSubmit" textT="action.submit" />
	</div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { BaseButton, BaseTip } from '@/components/base'

const emits = defineEmits(['finish'])
const inputListRef = ref<HTMLInputElement>()

let code: string

const onInput = (event: KeyboardEvent, index: number) => {
	const inputList = Array.from(inputListRef.value!.children)
	const { key } = event
	if (/\d/.test(key)) {
		const currInput: any = inputList[index]
		if (index < inputList.length - 1) {
			const input: any = inputList[index + 1]
			setTimeout(() => input.focus())
		}
		setTimeout(() => {
			code = inputList.reduce((prev, item: any) => prev + item.value, '')
			if (code.length === 6) {
				currInput.blur()
				// runCheckCode({
				// 	...params?.value,
				// 	code
				// })
			}
		})
	} else if (key === 'Backspace') {
		if (index > 0) {
			const currInput: any = inputList[index]
			const currValue = currInput.value
			setTimeout(() => {
				if (currValue) {
					currInput.value = ''
				} else {
					const prevInput: any = inputList[index - 1]
					prevInput.focus()
					prevInput.value = ''
				}
			})
		}
	} else {
		event.preventDefault()
	}
}

const onSubmit = () => {
	emits('finish')
}
</script>
